package edu.sctu.jarime.june.day20150628.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by user19 on 2015/6/28.
 */
public class PostUtil {

    /**
     * 从接口获得Json数据
     *
     * @return
     * @throws IOException
     */
    public  String postJson(HashMap<String,String> paramMap) throws IOException{


        //对象处理
        URL url = new URL(PathUtil.HOME_VALUE);
        URLConnection urlConnection = url.openConnection();
        //配置
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;

        httpURLConnection.connect();
        //数据传输
        byte[] buffer =new byte[1024];
        int count = 0;

        OutputStream outputStream = httpURLConnection.getOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
        objectOutputStream.write(getPath(paramMap).getBytes());
        objectOutputStream.flush();
        objectOutputStream.close();
        InputStream inputStream = httpURLConnection.getInputStream();

        String json = "";
        while ((count=inputStream.read(buffer))!=-1){
            json = json + new String(buffer,0,count);
        }

        inputStream.close();

        return json;
    }


    /**
     * 得到路径
     * @return
     */
    public   String getPath(HashMap<String,String> paramMap ){
        String path = "";
        String param= "";

        Set entries = paramMap.entrySet();

        Iterator iter = entries.iterator();

        while (iter.hasNext()){
            Map.Entry entry = (Map.Entry)iter.next();
            Object key =entry.getKey();
            Object value =entry.getValue();
            param=value+"="+key;
            path=path+param+"&";
        }
        path = path.substring(0,path.length()-1);
        return path;
    }


}
